package tsi

import (
	MQTT "earth/mqtt"
	"encoding/json"

	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

// 发送遥测数据到平台
func SendTelemetry(deviceID string, v any) error {
	// 将payloadMap.values 转为json字符串
	valueBytes, err := json.Marshal(v)
	if err != nil {
		return err
	}
	logrus.Info("values:", string(valueBytes))
	payloadMap := map[string]interface{}{
		"device_id": deviceID,
		"values":    valueBytes,
	}
	payload, err := json.Marshal(payloadMap)
	if err != nil {
		return err
	}
	return MQTT.Publish(string(payload))
}

// 发送属性到平台
func SendProperty(deviceID string, v any) error {
	// 将payloadMap.values 转为json字符串
	valueBytes, err := json.Marshal(v)
	if err != nil {
		return err
	}
	logrus.Info("values:", string(valueBytes))
	var payloadMap map[string]interface{}
	if viper.GetString("version") == "new" {
		payloadMap = map[string]interface{}{
			"device_id": deviceID,
			"values":    valueBytes,
		}
	} else {
		payloadMap = map[string]interface{}{
			"token":  deviceID,
			"values": valueBytes,
		}
	}
	payload, err := json.Marshal(payloadMap)
	if err != nil {
		return err
	}
	return MQTT.PublishAttributes(deviceID, payload)
}

// 发送事件到平台
func SendEvent(deviceID string, params any, method string) error {
	valuesMap := map[string]interface{}{
		"method": method,
		"params": params,
	}
	valueBytes, err := json.Marshal(valuesMap)
	logrus.Info("values:", string(valueBytes))
	if err != nil {
		return err
	}
	payloadMap := map[string]interface{}{
		"device_id": deviceID,
		"values":    valueBytes,
	}
	payload, err := json.Marshal(payloadMap)
	if err != nil {
		return err
	}
	return MQTT.PublishEvent(deviceID, payload)
}
